<!-- 收件地址列表 -->
<template>
  <s-layout :bgStyle="{ color: '#FFF' }" title="代理商">
    <view v-if="status === 'finish'" class="content-box">
      <view class="image-box">
        <image src="/static/agent.jpg" mode="widthFix" />
        <view class="image-text">{{ agentInfo.name }}</view>
        <view class="image-wxCode">{{ agentInfo.userId }}</view>
        <view class="image-level">{{ getLevelName(agentInfo.level) }}</view>
        <view class="image-createTime">{{
          sheep.$helper.timeFormat(agentInfo.createTime, 'yyyy-mm-dd hh:MM:ss')
        }}</view>
        <view class="image-licenseNo">{{ agentInfo.licenseNo }}</view>
      </view>
    <su-fixed
      bottom
      :opacity="false"
      bg=""
      placeholder
      :noFixed="false"
      :index="10"
    >
       <view class="footer-box ss-flex-col ss-row-between ss-p-20" >
        <view class="ss-m-b-20" >
          <button class="ss-reset-button add-btn ui-Shadow-Main" @tap="updateInfo">重新申请</button>
        </view>
      </view>
      </su-fixed>
    </view>
    <uni-forms
      v-else
      ref="agentFormRef"
      v-model="state"
      :rules="rules"
      validateTrigger="bind"
      labelWidth="160"
      labelAlign="left"
      border
      :labelStyle="{ fontWeight: 'bold' }"
    >
      <view class="bg-white form-box ss-p-x-30">
        <uni-forms-item v-if="status !== 'edit'" label="审批状态" class="form-item">
          <view v-if="agentStatus" style="line-height: 40px">{{
            agentStatus === '1' ? '审批中' : agentStatus === '2' ? '审核通过' : '审核未通过'
          }}</view>
        </uni-forms-item>
        <uni-forms-item name="level" label="代理商等级" class="form-item">
          <radio-group @change="onChange">
            <label class="radio ss-flex ss-col-center" v-for="item in agentLevel" :key="item">
              <radio
                :value="item"
                color="var(--ui-BG-Main)"
                :checked="item.value === state.level"
                :disabled="status !== 'edit'"
              />
              <view class="ss-flex-1 ss-p-20">{{ item.label }}</view>
            </label>
          </radio-group>
        </uni-forms-item>

        <uni-forms-item name="voucherType" label="凭证类型" class="form-item">
          <radio-group @change="onVoucherChange">
            <label
              class="radio ss-flex ss-col-center"
              v-for="item in agentVoucherLevel"
              :key="item"
            >
              <radio
                :value="item"
                :disabled="status !== 'edit'"
                color="var(--ui-BG-Main)"
                :checked="item.value === state.voucherType"
              />
              <view class="ss-flex-1 ss-p-20">{{ item.label }}</view>
            </label>
          </radio-group>
        </uni-forms-item>
        <uni-forms-item name="voucher" label="凭证" class="form-item">
          <s-uploader
            v-if="!state.voucher && status === 'edit'"
            file-mediatype="image"
            :imageStyles="{ width: 50, height: 50, border: false }"
            @select="onSelect({ data: $event })"
          >
            <image
              class="icon"
              :src="sheep.$url.static('/static/img/shop/chat/image.png')"
              mode="aspectFill"
            ></image>
          </s-uploader>
          <image v-else class="emoji-img" :src="state.voucher" @tap="onPreview" />
          <view v-if="state.voucher && status === 'edit'" class="m-l" @tap="ondelePic">删除</view>
        </uni-forms-item>
      </view>
    </uni-forms>
    <su-fixed
      v-if="status === 'edit'"
      bottom
      :opacity="false"
      bg=""
      placeholder
      :noFixed="false"
      :index="10"
    >
      <view class="footer-box ss-flex-col ss-row-between ss-p-20" style="width: 100%;box-sizing: border-box;">
        <view class="ss-m-b-20" style="display: flex; justify-content: space-around;">
          <button v-if="backBtn" class="ss-reset-button back-btn ui-Shadow-Main" @tap="status = 'finish'">返回</button>
          <button class="ss-reset-button add-btn ui-Shadow-Main" @tap="onSave">申请</button>
        </view>
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
  import { reactive, ref, unref, nextTick } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import DictApi from '@/sheep/api/system/dict';
  import ArticleApi from '@/sheep/api/promotion/agent';
  import FileApi from '@/sheep/api/infra/file';
  import sheep from '@/sheep';
  const agentFormRef = ref(null);
  const status = ref('view');
  const agentStatus = ref('');
  const rules = {
    level: {
      rules: [
        {
          required: true,
          trigger: 'change',
          errorMessage: '请选择代理商级别',
        },
      ],
    },
    voucherType: {
      rules: [
        {
          required: true,
          trigger: 'change',
          errorMessage: '请选择代理商凭证类型',
        },
      ],
    },
    voucher: {
      rules: [
        {
          required: true,
          errorMessage: '请上传凭证',
        },
      ],
    },
  };
  const agentInfo = ref({});
  const state = reactive({
    level: '', // 代理商级别
    voucherType: '', // 代理商凭证类型
    voucher: '', // 凭证
  });
  const backBtn = ref(false)
  const updateInfo=async()=>{
  
    await getRecord();
    status.value = 'edit'
  }
  function onChange(e) {
    state.level = e.detail.value.value;
    nextTick(() => {
      unref(agentFormRef).validateField('level');
    });
  }
  function onVoucherChange(e) {
    state.voucherType = e.detail.value.value;
    nextTick(() => {
      unref(agentFormRef).validateField('voucherType');
    });
  }
  const agentLevel = ref('');
  const agentVoucherLevel = ref('');
  async function getAgentInfo() {
    const { code, data } = await ArticleApi.getAgent();
    if (code !== 0) {
      return;
    }
    if (!data) {
      getRecord();
    } else {
      status.value = 'finish';
      agentInfo.value = data;
      backBtn.value = true
    }
  }
  const getLevelName = (value) => {
    console.log(value);
    if (!value) return '';
    console.log('agentLevel', agentLevel.value);
    const item = agentLevel.value.find((item) => item.value == value);
    console.log(item);
    return item ? item.label : '';
  };

  // 获取代理商级别字典
  async function getDictDataListByAgentLevel() {
    let { code, data } = await DictApi.getDictDataListByType('agent_level');
    if (code !== 0) {
      return;
    }
    if (data && data.length > 0) {
      agentLevel.value = data;
    }
  }
  // 获取代理商付款凭证类型字典
  async function getDictDataListByAgentVoucherLevel() {
    let { code, data } = await DictApi.getDictDataListByType('agent_voucher_type');
    if (code !== 0) {
      return;
    }
    if (data && data.length > 0) {
      agentVoucherLevel.value = data;
    }
  }
  async function getRecord() {
    const { code, data } = await ArticleApi.getRecord();
    if (code !== 0) {
      return;
    }
    if (!data) {
      status.value = 'edit';
    } else {
      status.value = 'view';
      state.level = data.level + '';
      state.voucherType = data.voucherType + '';
      state.voucher = data.voucher;
      agentStatus.value = data.status;
    }
    console.log('data======', data);
  }
  onLoad(() => {
    getDictDataListByAgentLevel();
    getDictDataListByAgentVoucherLevel();
    getAgentInfo();
  });
  // 保存收货地址
  const onSave = async () => {
    // 参数校验
    const validate = await unref(agentFormRef)
      .validate()
      .catch((error) => {
        console.log('error: ', error);
      });
    if (!validate) {
      return;
    }

    // 提交请求
    const res = await ArticleApi.postAgent(state);
    console.log('====', res);
    if (res.code !== 0) {
      return;
    }
    status.value = 'view';
    getRecord();
  };
  async function onSelect({ type, data }) {
    const res = await FileApi.uploadFile(data.tempFiles[0].path);
    console.log(res);
    state.voucher = res.data;
    nextTick(() => {
      unref(agentFormRef).validateField('voucher');
    });
  }
  const onPreview = () => {
    uni.previewImage({
      urls: [state.voucher],
    });
  };
  function ondelePic() {
    state.voucher = '';
  }
</script>

<style lang="scss" scoped>
  .footer-box {
    .add-btn {
      flex: 1;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      border-radius: 80rpx;
      font-size: 30rpx;
      font-weight: 500;
      line-height: 80rpx;
      color: $white;
      position: relative;
      z-index: 1;
      padding: 0 20rpx;
    }
    .back-btn {
      background: linear-gradient(90deg, #898989, rgb(127 127 127 / 100%));
      border-radius: 2.5rem;
      font-size: 0.9375rem;
      font-weight: 500;
      line-height: 2.5rem;
      color: #ffffff;
      position: relative;
      z-index: 1;
      padding: 0 0.625rem;
      width: 30%;
    }

    .sync-wxaddress {
      flex: 1;
      line-height: 80rpx;
      background: $white;
      border-radius: 80rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: $dark-6;
      margin-right: 18rpx;
    }
  }
  .icon {
    width: 50rpx;
    height: 50rpx;
    margin-bottom: 21rpx;
  }
  .emoji-img {
    width: 250rpx;
    height: 250rpx;
    display: inline-block;
    margin: 10rpx;
  }
  .m-l {
    margin-left: 10rpx;
  }
  .image-box {
    width: 750rpx;
    position: relative;
    font-size: 18rpx;
    image {
     width: 100%;
      height: auto;
      display: block;
    }
    .image-text {
      position: absolute;
      top: 365rpx;
      left: 200rpx;
    }
    .image-wxCode {
      position: absolute;
      top: 365rpx;
      left: 358rpx;
    }
    .image-level {
      position: absolute;
      top: 400rpx;
      left: 267rpx;
    }
    .image-createTime {
      position: absolute;
      top: 540rpx;
      left: 230rpx;
    }
    .image-licenseNo {
      position: absolute;
      top: 575rpx;
      left: 230rpx;
    }
  }
  .content-box {
    width: 100%;
    min-height: calc(100vh - 250rpx);
    display: flex;
    justify-content: center;
    align-items: center; /* 顶部对齐，可根据需要调整 */
    box-sizing: border-box;
    flex-wrap: wrap;
  }
</style>
